#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <assert.h>
#include <stdlib.h>
typedef void (*func_t)(); //函数指针
func_t task_[3];
void task1()
{
    printf("task1\n");
}
void task2()
{
    printf("task2\n");
}    
void task3()
{
    printf("task3\n");
}

void add_task()
{
    task_[0] = task1;
    task_[1] = task2;
    task_[2] = task3;
}
int main()
{
    pid_t id = fork();
    assert(id != -1);
    add_task();
    if(id == 0)
    {
        //child
        int cnt = 3;
        while(cnt--)
        {
            printf("i am child, pid: %d, ppid: %d\n", getpid(), getppid());
            sleep(1);
        }
        _exit(20);

    }
   // int status;
   // pid_t ret = waitpid(id, &status, 0);
   // //if(ret > 0)
   // //{
   // //    if(WIFEXITED(status) > 0)
   // //    {
   // //        printf("wait success, exit code: %d\n", WEXITSTATUS(status));
   // //    }
   // //}
   // if(ret > 0)
   // {
   //     printf("wait success, exit code: %d, exit sig: %d\n", status >> 8 & 0xff, status & 0x7f);
   // }
   int status = 0;
   while(1)
   {
       pid_t ret = waitpid(id, &status, WNOHANG);
       if(ret == 0)
       {    
           //等待成功，但子进程未退出
           printf("parent runing........\n");
           for(int i = 0; i < 3; ++i)
           {
               task_[i]();
           }
           sleep(1);
       }
       else if(ret > 0)
       {
           //等待成功，子进程退出 
           printf("wait success, exit code: %d, exit sig: %d\n", status >> 8 & 0xff, status & 0x7f);
           break; 

       }
       else 
       {
           //waitpid调用失败
           printf("wait fail\n");
           break;
       }
   }
    
    return 0;
}
